import {Crawler, Analyser, Saver} from "./interface";
import BaiduAnalyser from "./BaiduAnalyser";
import superagent from "superagent";
import fs from 'fs';
import path from "path";

export class App implements Crawler, Saver {
    constructor(private src: string, private file: string, private analyser: Analyser) {
    }

    async go() {
        let str = await this.crawl(this.src);
        let obj = this.analyser.analyse(str);
        this.save(this.file, obj);
    }

    async crawl(src: string) {
        let ret = await superagent.get(src);
        return ret.text;
    }

    save(file: string, obj: object): void {
        let data = JSON.stringify(obj)+ ',\n';
        let msg = '写入成功';
        file = path.resolve(__dirname, file);
        fs.appendFile(file, data, err => {
            if(err)
                msg = '写入失败';
            console.log(msg);
        });
    }
}

let src = 'http://www.baidu.com';
let analyser = new BaiduAnalyser();
let fname = 'baidu.txt'
let app = new App(src, fname, analyser);
app.go();
